const DEFAULT_CONFIG = {
  baseURL: 'http://localhost:9999', // 公共基础URL
  timeout: 10000, // 默认超时时间
  header: {
    'Content-Type': 'application/json'
  }
};

const config = {
  ...DEFAULT_CONFIG
};
const interceptors = {
  request: [],
  response: []
}

const runInterceptorChain = async (chain, initialValue) => {
  let value = initialValue;
  for (const interceptor of chain) {
    value = await interceptor(value);
  }
  return value;
}

const addRequestInterceptor = function (interceptor) {
  interceptors.request.push(interceptor);
}
const addResponseInterceptor = function (interceptor) {
  interceptors.response.push(interceptor);
}

function objectToQueryString(params, encode = true) {
  if (!params || typeof params !== 'object') {
    return '';
  }
  
  const parts = [];
  
  // 递归处理嵌套对象
  function processValue(key, value) {
    if (Array.isArray(value)) {
      // 处理数组类型
      value.forEach(item => {
        processValue(`${key}[]`, item);
      });
    } else if (value && typeof value === 'object') {
      // 处理嵌套对象
      Object.keys(value).forEach(subKey => {
        processValue(`${key}[${subKey}]`, value[subKey]);
      });
    } else if (value !== null && value !== undefined) {
      // 处理基本类型
      const encodedKey = encode ? encodeURIComponent(key) : key;
      const encodedValue = encode ? encodeURIComponent(value) : value;
      parts.push(`${encodedKey}=${encodedValue}`);
    }
  }
  
  // 遍历所有参数
  Object.keys(params).forEach(key => {
    const value = params[key];
    processValue(key, value);
  });
  
  return parts.join('&');
}

const request = async (options) => {
  // 合并配置
  const mergedConfig = {
    ...config,
    ...options,
    header: {
      ...config.header,
      ...(options.header || {})
    }
  };

  // 处理路径参数
  let finalUrl = mergedConfig.baseURL + mergedConfig.url;
  if (mergedConfig.pathParams) {
    Object.keys(mergedConfig.pathParams).forEach(key => {
      finalUrl = finalUrl.replace(`{${key}}`, mergedConfig.pathParams[key]);
    });
  }

  // 处理查询参数
  if (mergedConfig.params && Object.keys(mergedConfig.params).length > 0) {
    const params = objectToQueryString(mergedConfig.params);
    finalUrl += (finalUrl.includes('?') ? '&' : '?') + params.toString();
  }

  // 创建请求配置
  const requestConfig = {
    url: finalUrl,
    method: mergedConfig.method || 'GET',
    header: mergedConfig.header,
    timeout: mergedConfig.timeout,
    data: mergedConfig.data || {}
  };

  try {
    // 执行请求拦截器
    let modifiedConfig = await runInterceptorChain(
      interceptors.request,
      requestConfig
    );

    // 发送请求
    const response = await new Promise((resolve, reject) => {
      modifiedConfig.fail = reject;
      modifiedConfig.success = resolve;
      wx.request(modifiedConfig);
    });

    // 执行响应拦截器
    return await runInterceptorChain(
      interceptors.response,
      response
    );
  } catch (error) {
    // 错误处理
    console.error('请求失败:', error);
    throw error;
  }
}

// 封装GET请求
const get = (url, params = {}, config = {}) => {
  return request({
    url,
    method: 'GET',
    params,
    ...config
  });
}

// 封装POST请求
const post = (url, data = {}, config = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...config
  });
}

// 封装PUT请求
const put = (url, data = {}, config = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...config
  });
}

// 封装DELETE请求
const del = (url, params = {}, config = {}) => {
  return request({
    url,
    method: 'DELETE',
    params,
    ...config
  });
}

// 封装带路径参数的请求
const getWithPath = (url, pathParams = {}, config = {}) => {
  return request({
    url,
    method: 'GET',
    pathParams,
    ...config
  });
}


// 3. 添加请求拦截器（添加Token）
addRequestInterceptor(config => {
  const token = wx.getStorageSync('token');
  if (token) {
    config.header.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 4. 添加响应拦截器（处理错误）
addResponseInterceptor(response => {
  console.log("请求返回： ", response)
  if (response.data.code >= 400 && response.data.code < 500) {
    const errorMap = {
      401: '未授权，请重新登录',
      403: '拒绝访问',
      404: '资源不存在',
    };
    const message = errorMap[response.statusCode] || `请求失败: ${response.statusCode}`;
    wx.showToast({
      title: message,
      icon: 'none'
    });
    wx.removeStorageSync('token')
    setTimeout(() => {
      wx.redirectTo({
        url: '/pages/login/index',
        success:function (params) {
          wx.removeStorageSync('token')
        }
      })
    }, 500)
    throw new Error(message);
  }
  if(response.data.code >= 500) {
    wx.showToast({
      title: response.data.msg,
      icon:'none'
    })
    throw new Error(response.data.msg);
  }
  return response.data;
});

module.exports = {
  post,
  get,
  put,
  del,
  getWithPath
}